package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"house123/C/srv/house"
	"house123/C/srv/internal/svc"
	"house123/C/srv/model/mysql"
	"house123/C/srv/pkg"
	"strconv"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *house.OrderAddRequest) (*house.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	goods := mysql.Goods{}

	mysql.DB.Where("id=?", in.GoodsId).Find(&goods)

	if goods.Stock < in.Num {
		logx.Error("库存不足")
		return nil, fmt.Errorf("库存不足")
	}

	OrderSn := uuid.NewString()
	var o = mysql.Order{
		UserId:  in.UserId,
		OrderSn: OrderSn,
		Amount:  goods.Price * float64(in.Num),
		Payment: "1",
		Status:  "1",
	}
	var og = mysql.OrderGoods{
		GoodsId: in.GoodsId,
		OrderId: int64(o.ID),
		Title:   goods.Title,
		Cover:   goods.Cover,
		Text:    goods.Text,
		Price:   goods.Price,
		Status:  goods.Status,
		Stock:   goods.Stock,
	}
	mysql.CreateAnimals(&o, &og)

	amount := strconv.FormatFloat(goods.Price, 'f', 2, 64)

	alipay := pkg.NewAlipay()

	pay := alipay.Pay(goods.Title, o.OrderSn, amount)
	return &house.OrderAddResponse{Success: true, Url: pay}, nil
}
